package com.lagou.sqlSession;

import com.lagou.config.BoundSql;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import com.lagou.utils.GenericTokenParser;
import com.lagou.utils.ParameterMapping;
import com.lagou.utils.ParameterMappingTokenHandler;


import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class simpleExecutor implements Executor {
    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {

        PreparedStatement preparedStatement = getPreparedStatement(configuration, mappedStatement, params);
        //执行sql
        ResultSet set = preparedStatement.executeQuery();

        String resultType = mappedStatement.getResultType();
        Class<?> resultClassType = getClassType(resultType);
        ArrayList<Object> resultObjects = new ArrayList<>();
        //封装返回结果集
        while (set.next()) {
            Object o = resultClassType.newInstance();
            ResultSetMetaData metaData = set.getMetaData();
            for (int i = 1; i < metaData.getColumnCount()+1; i++) {
                String columnName = metaData.getColumnName(i);
                Object object = set.getObject(columnName);

                //使用泛着或者内省，根据数据库表和实体的对应关系，完成封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultClassType);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o, object);

            }
            resultObjects.add(o);
        }
        return (List<E>) resultObjects;
    }

    public PreparedStatement getPreparedStatement(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        Connection connection = configuration.getDataSource().getConnection();
        String sql = mappedStatement.getSql();

        //设置参数
        BoundSql boundSql = getBoundSql(sql);
        String parameterType = mappedStatement.getParameterType();
        Class<?> parameterClassType = getClassType(parameterType);
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSql());
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();

        //传入的为单个对象
        if (parameterMappings.size()>params.length)
        {
           for (int i = 0; i < parameterMappings.size(); i++)
           {
               ParameterMapping parameterMapping = parameterMappings.get(i);
               String content = parameterMapping.getContent();
               Field declaredField = parameterClassType.getDeclaredField(content);
               //暴力访问
               declaredField.setAccessible(true);
               Object o = declaredField.get(params[0]);
               preparedStatement.setObject(i + 1, o);
           }
        }
        else{
            for (int i = 0; i < parameterMappings.size(); i++) {
                ParameterMapping parameterMapping = parameterMappings.get(i);
                String content = parameterMapping.getContent();
                //反射
                Field declaredField = parameterClassType.getDeclaredField(content);
                //暴力访问
                declaredField.setAccessible(true);
                Object o = declaredField.get(params[i]);
                preparedStatement.setObject(i + 1, o);
            }
        }


        return preparedStatement;
    }

    public int update(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        PreparedStatement preparedStatement = getPreparedStatement(configuration, mappedStatement, params);
        //执行sql
        int i = preparedStatement.executeUpdate();
        return i;
    }

    private BoundSql getBoundSql(String sql) {
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        String parseSql = genericTokenParser.parse(sql);
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();

        BoundSql boundSql = new BoundSql(parseSql, parameterMappings);
        return boundSql;
    }


    private Class<?> getClassType(String parameterType) throws ClassNotFoundException {
        Class<?> aClass = null;
        if (parameterType != null) {
            aClass = Class.forName(parameterType);
        }
        return aClass;
    }
}
